package com.example.userservice.controller;

import com.example.userservice.client.HomeworkClient;
import com.example.userservice.entity.user_account;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/student")
public class StudentHomeworkController {
    
    @Autowired
    private HomeworkClient homeworkClient;
    
    // 获取学生的作业列表
    @GetMapping("/homeworks")
    @ResponseBody
    public Object getStudentHomeworks(HttpSession session) {
        user_account user = (user_account) session.getAttribute("user");
        if (user == null) {
            return "未登录";
        }
        
        try {
            return homeworkClient.getStudentHomeworks(user.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return "获取作业列表失败: " + e.getMessage();
        }
    }
    
    // 学生提交作业
    @PostMapping("/homework/submit")
    @ResponseBody
    public String submitHomework(@RequestParam int homeworkId,
                                @RequestParam String contentText,
                                @RequestParam(required = false) String fileUrl,
                                HttpSession session) {
        user_account user = (user_account) session.getAttribute("user");
        if (user == null) {
            return "未登录";
        }
        
        try {
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("homeworkId", homeworkId);
            requestBody.put("userId", user.getId());
            requestBody.put("contentText", contentText);
            requestBody.put("fileUrl", fileUrl);
            
            return homeworkClient.submitHomework(requestBody);
        } catch (Exception e) {
            e.printStackTrace();
            return "提交作业失败: " + e.getMessage();
        }
    }
    
    // 获取学生特定作业的提交状态
    @GetMapping("/homework/{homeworkId}/submission")
    @ResponseBody
    public Object getStudentHomeworkSubmission(@PathVariable int homeworkId, HttpSession session) {
        user_account user = (user_account) session.getAttribute("user");
        if (user == null) {
            return "未登录";
        }
        
        try {
            return homeworkClient.getStudentHomeworkSubmission(user.getId(), homeworkId);
        } catch (Exception e) {
            e.printStackTrace();
            return "获取提交状态失败: " + e.getMessage();
        }
    }
}
